//
//  SettingController.m
//  Budejie
//
//  Created by 远成物流 on 2017/6/1.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "SettingController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "BFileManager.h"

#define CachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

@interface SettingController ()

@property(nonatomic,assign)NSInteger totalSize;

@end

static NSString * const cellID = @"SettingCell";

@implementation SettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"jump" style:UIBarButtonItemStylePlain target:self action:@selector(jumpAction)];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [SVProgressHUD showWithStatus:@"正在计算缓存大小..."];
    
    [BFileManager getFileSize:CachePath completion:^(NSInteger totalSize) {
        
        _totalSize = totalSize;
        
        [self.tableView reloadData];
        
        [SVProgressHUD dismiss];
    }];
}

-(void)jumpAction{
    
}

#pragma mark - UITableView datasource & delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    cell.textLabel.text = [self getSize];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [BFileManager removeDirectoryPath:CachePath];
    
    _totalSize = 0;
    
    [self.tableView reloadData];
}

//获取文件大小
-(NSString *)getSize{
    NSInteger totalSize = _totalSize;
    NSString *size = @"清除缓存";
    
    if (totalSize > 1000 * 1000) {
        //MB
        CGFloat fileSize = totalSize / 1000.0 / 1000.0;
        size = [NSString stringWithFormat:@"%@(%.1fMB)",size,fileSize];
    }else if (totalSize > 1000){
        //KB
        CGFloat fileSize = totalSize / 1000.0;
        size = [NSString stringWithFormat:@"%@(%.1fkB)",size,fileSize];
    }else if (totalSize > 0){
        //B
        size = [NSString stringWithFormat:@"%@(%.ldB)",size,totalSize];
    }else{
        
    }
    
    return size;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
